package com.campus.payment.service;

import com.campus.payment.dto.ProfitSharingRequestDTO;
import com.campus.payment.dto.ProfitSharingResponseDTO;
import com.wechat.pay.java.service.profitsharing.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 分账服务类
 *
 * @author ZhaoYuJie
 * @since 2025-01-15
 */
@Slf4j
@Service
public class ProfitSharingService {

    @Autowired
    private WechatPayService wechatPayService;

    /**
     * 添加分账接收方
     *
     * @param subMchid 子商户号
     * @param type 接收方类型：MERCHANT_ID-商户号，PERSONAL_OPENID-个人OpenID
     * @param account 接收方账号
     * @param name 接收方名称
     * @param relationshipType 与分账方的关系类型
     * @return 是否添加成功
     */
    public boolean addReceiver(String subMchid, String type, String account, String name, String relationshipType) {
        try {
            AddReceiverResponse response = wechatPayService.addProfitSharingReceiver(subMchid, type, account, name, relationshipType);
            return response != null;
        } catch (Exception e) {
            log.error("添加分账接收方失败，接收方账号：{}", account, e);
            return false;
        }
    }

    /**
     * 请求分账
     *
     * @param request 分账请求
     * @return 分账响应
     */
    public ProfitSharingResponseDTO createProfitSharing(ProfitSharingRequestDTO request) {
        try {
            // 转换接收方列表
            List<CreateOrderReceiver> receivers = request.getReceivers().stream()
                    .map(this::convertToCreateOrderReceiver)
                    .collect(Collectors.toList());

            // 调用微信分账API
            OrdersEntity response = wechatPayService.createProfitSharingOrder(
                    request.getSubMchid(),
                    request.getAppid(),
                    request.getTransactionId(),
                    request.getOutOrderNo(),
                    receivers,
                    request.getUnfreezeUnsplit()
            );

            // 转换响应
            return convertToProfitSharingResponse(response);
        } catch (Exception e) {
            log.error("请求分账失败，分账单号：{}", request.getOutOrderNo(), e);
            throw new RuntimeException("请求分账失败", e);
        }
    }

    /**
     * 查询分账结果
     *
     * @param subMchid 子商户号
     * @param transactionId 微信支付订单号
     * @param outOrderNo 商户分账单号
     * @return 分账响应
     */
    public ProfitSharingResponseDTO queryProfitSharing(String subMchid, String transactionId, String outOrderNo) {
        try {
            OrdersEntity response = wechatPayService.queryProfitSharingOrder(subMchid, transactionId, outOrderNo);
            return convertToProfitSharingResponse(response);
        } catch (Exception e) {
            log.error("查询分账结果失败，分账单号：{}", outOrderNo, e);
            throw new RuntimeException("查询分账结果失败", e);
        }
    }

    /**
     * 转换接收方DTO为微信API请求对象
     */
    private CreateOrderReceiver convertToCreateOrderReceiver(ProfitSharingRequestDTO.ReceiverDTO receiverDTO) {
        CreateOrderReceiver receiver = new CreateOrderReceiver();
        receiver.setType(receiverDTO.getType());
        receiver.setAccount(receiverDTO.getAccount());
        receiver.setAmount(receiverDTO.getAmount().longValue());
        receiver.setDescription(receiverDTO.getDescription());
        return receiver;
    }

    /**
     * 转换微信API响应为分账响应DTO
     */
    private ProfitSharingResponseDTO convertToProfitSharingResponse(OrdersEntity ordersEntity) {
        ProfitSharingResponseDTO response = new ProfitSharingResponseDTO();
        response.setOrderId(ordersEntity.getOrderId());
        response.setOutOrderNo(ordersEntity.getOutOrderNo());
        response.setTransactionId(ordersEntity.getTransactionId());
        response.setState(ordersEntity.getState().name());

        // 转换接收方列表
        if (ordersEntity.getReceivers() != null) {
            List<ProfitSharingResponseDTO.ReceiverDetailDTO> receiverDetails = ordersEntity.getReceivers().stream()
                    .map(this::convertToReceiverDetailDTO)
                    .collect(Collectors.toList());
            response.setReceivers(receiverDetails);
        }

        return response;
    }

    /**
     * 转换微信API接收方响应为接收方明细DTO
     */
    private ProfitSharingResponseDTO.ReceiverDetailDTO convertToReceiverDetailDTO(OrderReceiverDetail orderReceiver) {
        ProfitSharingResponseDTO.ReceiverDetailDTO detail = new ProfitSharingResponseDTO.ReceiverDetailDTO();
        detail.setAmount(orderReceiver.getAmount().intValue());
        detail.setDescription(orderReceiver.getDescription());
        detail.setType(orderReceiver.getType().name());
        detail.setAccount(orderReceiver.getAccount());
        detail.setResult(orderReceiver.getResult().name());
        if(orderReceiver.getFailReason() != null){
            detail.setFailReason(orderReceiver.getFailReason().name());
        }
        detail.setDetailId(orderReceiver.getDetailId());
        
        // 转换完成时间
        if (orderReceiver.getFinishTime() != null) {
            try {
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss+08:00");
                detail.setFinishTime(LocalDateTime.parse(orderReceiver.getFinishTime(), formatter));
            } catch (Exception e) {
                log.warn("解析分账完成时间失败：{}", orderReceiver.getFinishTime());
            }
        }
        
        return detail;
    }
}